<template>
  <div class="chart-item-container">
    <div ref="chartRef" class="chart-item"></div>
  </div>
</template>

<script lang="ts">
  import useEcharts from '@/hooks/useEcharts';
  import { defineComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
  import { dispose } from 'echarts';
  import { object } from 'vue-types';

  export default defineComponent({
    name: 'EmotionChart',
    props: {
      dataModel: {
        type: Array || object,
        default: () => {
          return {};
        },
      },
    },
    setup(props) {
      const last = ref<any>({
        bytesSent: '0B',
        bytesRecv: '0B',
        down: '0',
        up: '0',
      });
      const s = ref<any>([]);
      const x = ref<any>([]);
      let data = props.dataModel?.data;
      let list = data.list;
      list.forEach((item: any) => {
        if (item.date) {
          x.value.push(item.date);
        }
        s.value.push(item.top_num);
      });
      const option = ref({
        xAxis: {
          type: 'category',
          data: x.value,
        },
        yAxis: {
          type: 'value',
        },
        calculable: true,
        toolbox: {
          show: true,
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        tooltip: {
          // trigger: 'axis',
          formatter(params) {
            return `
        天数：${params.data.title} </br>
        数值：${params.data.value}
        `;
          },
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        series: [
          {
            data: s.value,
            type: 'bar',
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' },
              ],
            },
            markLine: {
              data: [{ type: 'average', name: '平均值' }],
            },
          },
        ],
      });

      const chartRef = ref<HTMLDivElement | null>(null);

      onBeforeUnmount(() => {
        if (chartRef.value !== null) {
          dispose(chartRef.value as HTMLDivElement);
        }
      });
      onMounted(() => {
        setTimeout(() => {
          nextTick(() =>
            useEcharts(chartRef.value as HTMLDivElement).setOption(option.value)
          );
        }, 10);
      });
      return {
        chartRef,
        last,
      };
    },
  });
</script>

<style scoped>
  .chart-item-container {
    width: 100%;

    .chart-item {
      height: 200px;
    }
  }

  .light-green {
    height: 108px;
    background-color: rgba(0, 128, 0, 0.12);
  }

  .green {
    height: 108px;
    background-color: rgba(0, 128, 0, 0.24);
  }
</style>
